/**
 */

package com.bei_en.teacher.third.pay.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.bei_en.common.util.SMS.ali.SMS;
import com.bei_en.teacher.admin.model.order.condition.OrderBasicCondition;
import com.bei_en.teacher.admin.model.order.vo.OrderBasicVo;
import com.bei_en.teacher.admin.service.order.OrderBasicService;
import com.bei_en.teacher.third.pay.bean.AliPayNotifyResult;
import com.bei_en.teacher.third.pay.web.alipay.AlipayNotify;

/**
 * @author Guocg
 *
 */
@Controller
@RequestMapping(value = "/pay/alipay")
public class AlipayController extends BaseController {
    @Autowired
    OrderBasicService orderBasicService;
//    public static final int PAY_TIME1 = 5;// 支付有效时间,30分钟
    public static int PAY_TIME1 = 30;// 支付有效时间,30分钟
    public static String partner = "2088421806097960";// 合作者身份ID
    public static String key = "rzg5w1cjk66fn6ubgc3hir87re42nnut";//GAKrTC/erz7bPFG9lmTuuw==
//    public static String notify_url1 = "http://amiurs.ngrok.natapp.cn/teacher/pay/alipay/notify";// 服务器异步通知页面路径
//    public static String notify_url = "http://www.ekaojiaoshi.com:8080/pay/alipay/notify";// 服务器异步通知页面路径
    public static String notify_url = "http://www.linwen.tunnel.phpor.me/teacher/pay/alipay/notify";// 服务器异步通知页面路径
 
    // 支付宝的公钥，无需修改该值
    public static String my_public_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB";

    public static String my_private_key = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAPHcdnXuiwoR0IfJ"+
"NKWhvm46JgOjiM9kxywqRlTATuKMOniP7p8Smuop3bFvnZ6aqiB63zCRhgA/l29d"+
"+zfVTBq9dULy5a0WxOfDLZD4ExD9/Eq8Ex7oy60SUKeQX1BzFcBqvrgq+d9MiI7A"+
"TGkm7cRrllbZNm5uXSm/jQSdtgdjAgMBAAECgYEAjYdi0pPqTNQr4Kl+40WIt9vT"+
"DuINVr80RcXfLgzynGNOe+pNykwK1uf00LXt2DfNQgBkxnkBnveXWBX4wa1RQFlQ"+
"xpeXVOv6wn5Cfj9RRt4WQcDLEGogCkhi6HUDXFuQ5yjEFBI/3ypKBmvcDScdrepY"+
"KedcbVXaDM0xLZcNI3ECQQD57ZZxR6+6LpM8zzWOBYYLb2LO5UgZflZShIi3eKt/"+
"liLLZ47UCX6TmaGLkym9AKyGDMahJVeraQHl+SE8+gR9AkEA97y0GbWCnql8PIhU"+
"Dy2Azh9FXHOrK/P606DpdVG1O5xUCRVPZnrGd5ZCfbjhZ1E0F9sN8iWXSXrLFLHe"+
"YhdhXwJAdx6qSaulMdPpEV6hY+N2FBUuvvXA+4WflwzcLLYy50ijpNbi2GT+E1Ny"+
"D5hAmHitweZs9Xla47PU18t58Bop8QJBALMgy+zG9MJ6dC1kubsbwMXJkKKPtFYc"+
"nOHGuOeug+etWooS0Y2c+sJfcIZtVvYYnh0dtBDBo4lq80psbgrpMusCQQDpBjOs"+
"XOsnc8jKs5GR3rFA6tlggnkTXIB9T2y9z5kTu44XtBIohm26fNl8UVVL8EqhWUaP"+
"TZH0p/r4RItqOMmn";

 
    /**
     * 异步通知
     * @author Guocg
     * @param request
     * @param vo
     * @param model
     * @param response
     * @return
     * @throws FrontException
     * @throws IOException 
     */
    @RequestMapping("/notify")
    public String notifyUrl2(HttpServletRequest request, AliPayNotifyResult vo, Model model,
	    HttpServletResponse response) throws IOException {

	// 获取支付宝GET过来反馈信息
	Map<String, String> params = new HashMap<String, String>();
	Map requestParams = request.getParameterMap();
	log.info(requestParams);
	for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
	    String name = (String) iter.next();
	    String[] values = (String[]) requestParams.get(name);
	    String valueStr = "";
	    for (int i = 0; i<values.length; i++) {
		valueStr = (i==values.length-1) ? valueStr+values[i] : valueStr+values[i]+",";
	    }
	    // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
	
	    params.put(name, valueStr);
	}
	if (params.isEmpty()) {
	    log.warn("参数为空");
	    response.setContentType("text/html;charset=UTF-8");
	    PrintWriter writer = response.getWriter();
	    writer.write("fail");
	    writer.close();
	    return null;
	}

	// 计算得出通知验证结果
	boolean verify_result = AlipayNotify.verify(params);

	if (verify_result) {// 验证成功
	    log.info("订单"+vo.getOut_trade_no()+"验证成功");

	    if (vo.getTrade_status().equals("TRADE_FINISHED")
		    ||vo.getTrade_status().equals("TRADE_SUCCESS")) {
	    	String code =vo.getOut_trade_no().split("-")[0];
    		OrderBasicCondition orderBasicCondition=new OrderBasicCondition();
    		orderBasicCondition.setOrderNum(code);
    		 List<OrderBasicVo>orderBasicVos= orderBasicService.findOrderBasicPage(orderBasicCondition);
    		if(!orderBasicVos.isEmpty()){
    			OrderBasicVo orderBasicVo=orderBasicVos.get(0);
    			orderBasicVo.setPaymentNumber(vo.getTrade_no());
    			orderBasicVo.setPaymentGateway(1+"");	
    			orderBasicVo.setPaymentTime((int)(new Date().getTime()/1000));
    			orderBasicVo.setStatus(2);
    			orderBasicService.updateSelective(orderBasicVo);
    		}
		 
	    }

	    return null;
	} else {

	    log.warn("订单"+vo.getOut_trade_no()+"验证失败");
	    response.setContentType("text/html;charset=UTF-8");
	    PrintWriter writer = response.getWriter();
	    writer.write("fail");
	    writer.close();
	    return null;
	}

    }
}
